import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xin_he/page/home/model/xin_he_goods_item_detail_entity.dart';
import '../../../utils/xin_he_event_bus.dart';
import '../../../utils/xin_he_storage.dart';
import '../../../utils/xin_he_user_data.dart';
import '../../login/xin_he_login_action.dart';
import '../../shopping_car/xin_he_goods_payment/xin_he_instant_buy/xin_he_instant_buy_view.dart';
import 'xin_he_goods_specification_model_entity.dart';
import '../../../service/xin_he_reqest.dart';
import '../../../utils/xin_he_toast.dart';
import 'xin_he_good_detail_state.dart';

class XinHeGoodDetailLogic extends GetxController {
  final XinHeGoodDetailState state = XinHeGoodDetailState();
  ScrollController scrollController = ScrollController();
  late Offset pointerStart;
  late Offset pointerEnd;
  double touchRangeX = 0;
  double touchRangeY = 0;
  double nextOffset = 0;
  int lastPage = 0;

  late int goodId;
  Rx<XinHeGoodsItemDetailEntity> model = XinHeGoodsItemDetailEntity().obs;
  // List tmpL = [];

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    goodId = Get.arguments??0;

  }

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();

    requestGoodsDetail();
  }

  void test(int index){
    print('xxxxxxDDDDD $index');

    if(lastPage == index)return;
    lastPage = index;
    animateToOffset(scrollController, Get.width * lastPage, (){});

  }


  requestGoodsDetail() async{

    Map<String,dynamic> ss = {
      'goodsId':goodId
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/goods/detailGoods',params: ss,isPost: false);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }


    Map <String,dynamic> json = result.data['data'] ??{};
    XinHeGoodsItemDetailEntity mod  = XinHeGoodsItemDetailEntity.fromJson(json);
    // mod.iconPath = 'https://xhyp.quexiaoer.cn/upload/goods-photo/goods-photo_20230703074806830_3210.png';

    model.value = mod;

    if(mod.iconPath!.isNotEmpty){
      if(mod.iconPath!.contains(';')){
        List urls = mod.iconPath!.split(';');
        state.images.value = urls;
      }else{
        state.images.value = [mod.iconPath!];
      }
    }

    if(mod.iconPath2 != null){
      if(mod.iconPath2!.contains(';')){
        List urls = mod.iconPath2!.split(';');
        state.bottomImages.value = urls;
      }else{
        state.bottomImages.value = [mod.iconPath2!];
      }
    }



    requestGoodSpecification();

  }

  // addToCart() async{
  //   Map<String,dynamic> ss = {
  //     'goodsId':model.value.id,
  //     'amount':5,
  //     'goodsPriceId':model.value.priceId,
  //     'orderType':'COMMON',
  //     'userId': xinHeUserData.userId.value,
  //     'zoneType':model.value.goodsZoneType??0
  //   };
  //   XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/shopcart/saveShopcart',params: ss,isPost: true);
  //
  //   if(!result.result){
  //     XinHeToast.center(result.data['message']);
  //     return ;
  //   }
  //
  //   if(result.data['code'] == 0){
  //     bus.emit(XinHeStorage.refreshCart);
  //
  //     XinHeToast.center('已加入到购物车');
  //   }
  //
  //
  // }

  buyNow()async{
    Map<String,dynamic> ss = {
      'goodsId':model.value.id,
      'amount':1,
      'goodsPriceId':model.value.priceId,
      'orderType':'COMMON',
      'zoneType':model.value.goodsZoneType??0
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/shopcart/saveBuyNow',params: ss,isPost: true);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }



  }

  ///查询商品规则
  requestGoodSpecification()async{
    Map<String,dynamic> ss = {
      'goodsId': model.value.id
    };
    XinHeRequestDataResult result = await XinHeHttpRequestData.requestUniversalPost(url: '/goodsPrice/queryGoodsPrice',params: ss,isPost: false,isShowLoading: true);

    if(!result.result){
      XinHeToast.center(result.data['message']);
      return ;
    }

    List dataList = result.data['data'] ??[];
    if(dataList.isNotEmpty) {

      List list = [];
      for(var e in dataList) {
        XinHeGoodsSpecificationModelEntity model = XinHeGoodsSpecificationModelEntity.fromJson(e);
        model.isSelected = false;
        list.add(model);
      }
      state.specificationList.value = list;

    }

  }

  toPage( int type) {

    if(xinHeUserData.appLoginState.value == false) {
      XinHeLoginAction.modalToLoginPage();

      return ;
    }

    Get.bottomSheet(const XinHeInstantBuyPage(),persistent: true,isScrollControlled: true,
        settings: RouteSettings(
            name: '/goods_detail/instant_buy',
            arguments: {'goodsModel':model.value, 'specM':state.specificationList.value , 'type': type }
        )
    );
  }

  PointerDownEventListener getPointDownListenerInHorizontal() {
    return (event) {
      pointerStart = event.position;
    };
  }

  PointerUpEventListener getPointUpListenerInHorizontal() {

    return (event){
      pointerEnd = event.position;
      touchRangeX = pointerStart.dx - pointerEnd.dx;
      touchRangeY =pointerStart.dy - pointerEnd.dy;

      double screenWidth = Get.width;
      //所有的操作必须要满足滑动距离>10才算是滑动
      if (touchRangeX.abs() < 10) {
        nextOffset = screenWidth * lastPage;
        animateToOffset(scrollController, nextOffset, () {
          if (lastPage < 0) {
            lastPage = 0;
          }
        });
        return;
      }
      //纵向操作大于横向操作三倍视为纵向操作
      //这个判断拦截只有在纵向操作距离大于20.0的时候才生效
      if (touchRangeX.abs() < touchRangeY.abs() && touchRangeY > 20) {
        nextOffset = screenWidth * lastPage;
        animateToOffset(scrollController, nextOffset, () {
          if (lastPage < 0) {
            lastPage = 0;
          }
        });
        return;
      }

      //如果滑动小于当前屏幕1/8，那么就回弹复原，超过则移动到下一页
      //跳转到下一页或者上一页或者不动
      if (touchRangeX > screenWidth / 8) {
        nextOffset = screenWidth * (lastPage + 1);
        print("animate to ${nextOffset}");
        animateToOffset(scrollController, nextOffset, () {
          lastPage++;
          if (lastPage >= state.images.length - 1) {
            lastPage = state.images.length - 1;
          }
        });
      } else if (touchRangeX < -1 * screenWidth / 8) {
        nextOffset = screenWidth * (lastPage - 1);
        print("animate to ${nextOffset}");
        animateToOffset(scrollController, nextOffset, () {
          lastPage--;
          if (lastPage < 0) {
            lastPage = 0;
          }
        });
      } else {
        animateToOffset(scrollController, screenWidth * lastPage, (){});
      }
    };

  }

  void animateToOffset(ScrollController controller, double offset,
      void Function() onScrollCompleted) {
    controller
        .animateTo(offset,
        duration: Duration(milliseconds: 200), curve: Curves.easeIn)
        .then((value) {
      if (onScrollCompleted != null) {
        onScrollCompleted();
      }
    }).catchError((e) {
      print(e);
    });
  }

}
